package com.logistics.service.Impl;

import com.logistics.dao.BaseDao;
import com.logistics.dao.UserDao;
import com.logistics.entity.User;
import com.logistics.service.UserService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Ranger on 2015/8/14.
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public BaseDao getBaseDao() {
        return userDao;
    }

    /**
     * 用户登录
     */
    @Override
    public User login(User user) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(User.class);
        detachedCriteria.add(Restrictions.eq("email", user.getEmail()));
        detachedCriteria.add(Restrictions.eq("password", user.getPassword()));
        List<User> list = userDao.search(detachedCriteria);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 注册用户
     */
    @Override
    public User register(User user) {
        if (user.getEmail().isEmpty() || user.getPassword().isEmpty()) { // 用户名和密码不为空
            return null;
        } else { // 检查数据中是否存在有相同Email的用户
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(User.class);
            detachedCriteria.add(Restrictions.eq("email", user.getEmail()));
            if (userDao.search(detachedCriteria).isEmpty()) { // 不存在相同Email的用户
                userDao.save(user);
                return user;
            } else { // 存在相同Email的用户
                return null;
            }
        }
    }
}
